import React from 'react';
import ProList from '@ant-design/pro-list';
import {PageContainer} from "@ant-design/pro-layout";
import {Link} from "umi";
import {search} from "@/pages/search/service";

const getUrl = ({pubType, id}) => {
  if (pubType === 'info')
    return `/info-${id}.html`;
  if (pubType === 'book')
    return `/product-${id}.html`;

  return `/archives-${id}.html`;
};

const Search = (props) => {
  const {loading, ...restProps} = props;
  const {location: {state = {wd: '',}}} = restProps;
  let param = {wd: '',};
  if (state?.wd && state.wd !== param.wd) {
    const { wd } = state;
    param = { wd };
    sessionStorage.setItem('wo_search', JSON.stringify(param));
  } else {
    const temp = JSON.parse(sessionStorage.getItem('wo_search'));
    if (temp && temp.wd) {
      param = temp;
    }
  }

  return (
    <PageContainer
      title={false}
      header={
        {
          breadcrumb: {
            routes: [
              {
                path: '/',
                breadcrumbName: '首页',
              },
              {
                path: '',
                breadcrumbName: `关键字 "${param.wd}" 的搜索结果`
              }
            ]
          }
        }
      }
    >
      <ProList
      search={{}} rowKey="id"
      headerTitle="查询结果"
      loading={loading}
      params={param}
      request={async (params, sorter, filter) => {
        const {wd, ...other} = params;
        const res = await search({
          wd: wd?? param.wd,
          ...other,
          sorter,
          filter});
        return Promise.resolve({
          total: res?.data?.total || 0,
          data: res?.data?.rows || [],
          success: true,
        });
      }}
      pagination={{pageSize: 5,}}
      metas={{
        title: {
          dataIndex: 'pubTitle',
          title: '标题',
          search: false,
          render: (dom, entity) => {
            return <Link to={getUrl(entity)} target="_blank" rel="noopener noreferrer">{dom}</Link>;
          }
        },
        wd: {
          title: '关键字',
          valueType: 'input',
        },
      }}
      />
    </PageContainer>
  );
};

export default Search;
